package com.foo.common.base.utils;

import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public enum ZipHelper {
    instance;
    private final static Logger LOGGER = LoggerFactory.getLogger(ZipHelper.class);
    private List<String> fileList = Lists.newArrayList();

    public void compressDirToZip(String sourceFolder, String outputZipFile)
            throws IOException {
        generateFileList(sourceFolder, new File(sourceFolder));
        zipIt(sourceFolder, outputZipFile);
    }

    private void zipIt(String sourceFolder, String zipFile) throws IOException {
        byte[] buffer = new byte[1024];
        String source = new File(sourceFolder).getName();
        try (FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos)) {
            LOGGER.info("Output to Zip : {}", zipFile);
            for (String file : this.fileList) {
                LOGGER.info("File Added :{}", file);
                ZipEntry ze = new ZipEntry(source + File.separator + file);
                zos.putNextEntry(ze);
                try (FileInputStream in = new FileInputStream(sourceFolder + File.separator + file)) {
                    int len;
                    while ((len = in.read(buffer)) > 0) {
                        zos.write(buffer, 0, len);
                    }
                }
            }
            zos.closeEntry();
            LOGGER.info("Folder successfully compressed");
        }
    }

    private void generateFileList(String sourceFolder, File node) {
        if (node.isFile()) {
            String file = node.toString();
            fileList.add(file.substring(sourceFolder.length() + 1, file.length()));
        }
        if (node.isDirectory()) {
            String[] subNote = node.list();
            if (subNote != null) {
                for (String filename : subNote) {
                    generateFileList(sourceFolder, new File(node, filename));
                }
            }
        }
    }
}

